package com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.dataobject.Points;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.dto.OrderDTO;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.mapper.PointsMapper;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.service.PointsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 积分服务实现类
 *
 * @author ziyucoding
 * @date 2023-04-03
 **/
@Service
public class PointsServiceImpl implements PointsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PointsMapper pointsMapper;

    Snowflake snowflake = new Snowflake(1, 1);

    @Override
    public void increasePoints(OrderDTO order) {
        // 入库之前先查询，实现幂等
        if (pointsMapper.selectCountById(order.getOrderNo()) > 0) {
            logger.info("积分添加完成，订单已处理。{}", order.getOrderNo());
        } else {
            Points points = new Points();
            points.setId(snowflake.nextId());
            points.setUserId(order.getUserId());
            points.setOrderNo(order.getOrderNo());
            Double amount = order.getAmount();
            points.setPoints(amount.intValue() * 10);
            points.setRemarks("商品消费共【" + order.getAmount() + "】元，获得积分" + points.getPoints());
            pointsMapper.insert(points);
            logger.info("已为订单号码{}增加积分。", points.getOrderNo());
        }
    }

}
